package com.onlineMIS.ORM.DAO.chainS.sales;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Repository;

import com.onlineMIS.ORM.DAO.BaseDAO;
import com.onlineMIS.ORM.DAO.chainS.report.ChainReportService;
import com.onlineMIS.ORM.entity.chainS.sales.ChainStoreSalesOrder;
import com.onlineMIS.ORM.entity.chainS.sales.EchartsInfoVO;
import com.onlineMIS.ORM.entity.chainS.user.ChainStore;
import com.onlineMIS.action.chainS.report.ChainReportActionFormBean;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.DateUtils;

@Repository
public class ChainStoreSalesOrderDaoImpl extends BaseDAO<ChainStoreSalesOrder> {
	
	/**
	 * to initialize the sales order
	 */
	public void initialize(ChainStoreSalesOrder salesOrder){
		this.getHibernateTemplate().initialize(salesOrder.getProductSet());
	}
	
	
	
	/**
	 * 获取天
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public List<ChainStoreSalesOrder> getChainStoreSalesOrders(Date startDate,Date endDate,Integer chainId,Integer userId,Boolean isHidden) {
		List<ChainStoreSalesOrder> orders = new ArrayList<ChainStoreSalesOrder>();
		List<Object> value_sale = new ArrayList<Object>();
		value_sale.add(startDate);
		value_sale.add(endDate);
		String sql = "";
		String groupSql = "GROUP BY orderDate";
		if (isHidden) {
			sql = "and (status = " + ChainStoreSalesOrder.STATUS_HIDE + " or status = " +ChainStoreSalesOrder.STATUS_COMPLETE+ ")";
		}else {
			sql = "and status = " +ChainStoreSalesOrder.STATUS_COMPLETE ;
		}
		
		// 单店铺查询统计
		if (chainId != null && chainId != 0 && chainId != Common_util.ALL_RECORD) {
			sql += "and chainStore.chain_id = ?";
			groupSql += ",chainStore.chain_id";
			value_sale.add(chainId);
		}
		if (userId != null && userId != -1) {
			sql += "and saler.user_id = ?";
			groupSql += ",saler.user_id";
			value_sale.add(userId);
		}
				
		String criteria = "SELECT SUM(totalQuantity),SUM(totalQuantityR),SUM(netAmount),SUM(netAmountR),orderDate FROM  ChainStoreSalesOrder WHERE orderDate between ? and ? " + sql + groupSql;
		
		List<Object> values = executeHQLSelect(criteria, value_sale.toArray(), null, true);
		
		if (values != null) {
			for (Object record : values ){
				Object[] records = (Object[])record;
				int quantity = Common_util.getInt(records[0]);
				int quantityR = Common_util.getInt(records[1]);
				double netAmount = Common_util.getDouble(records[2]);
				double netAmountR = Common_util.getDouble(records[3]);
				java.sql.Date orderDate = Common_util.getDate(records[4]);
				ChainStoreSalesOrder salesOrder = new ChainStoreSalesOrder();
				salesOrder.setTotalQuantity(quantity);
				salesOrder.setTotalQuantityR(quantityR);
				salesOrder.setNetAmount(netAmount);
				salesOrder.setNetAmountR(netAmountR);
				salesOrder.setOrderDate(orderDate);
				orders.add(salesOrder);
			}
		}
		
		return orders;
		
	}
	
	
	/**
	 * 获取周/年
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public ChainStoreSalesOrder getChainStoreSalesWeekOrders(Date startDate,Date endDate,Integer chainId,Integer userId,Boolean isHidden) {
		List<ChainStoreSalesOrder> orders = new ArrayList<ChainStoreSalesOrder>();
		List<Object> value_sale = new ArrayList<Object>();
		value_sale.add(startDate);
		value_sale.add(endDate);
		// 获取完成状态和隐藏状态单据
		String sql = "";							
		if (isHidden) {
			sql = "and (status = " + ChainStoreSalesOrder.STATUS_HIDE + " or status = " +ChainStoreSalesOrder.STATUS_COMPLETE+ ")";
		}else {
			sql = "and status = " +ChainStoreSalesOrder.STATUS_COMPLETE ;
		}
		
		// 总部查询指定单店铺
		if (chainId != null && chainId != 0  && chainId != Common_util.ALL_RECORD) {
			sql += "and chainStore.chain_id = ?";
			value_sale.add(chainId);
		}
		if (userId != null && userId != Common_util.ALL_RECORD) {
			sql += "and saler.user_id = ?";
			value_sale.add(userId);
		}
		
		String criteria = "SELECT SUM(totalQuantity),SUM(totalQuantityR),SUM(netAmount),SUM(netAmountR) FROM  ChainStoreSalesOrder WHERE orderDate between ? and ?" + sql;
		
		List<Object> values = executeHQLSelect(criteria, value_sale.toArray(), null, true);
		
		if (values != null) {
			for (Object record : values ){
				Object[] records = (Object[])record;
				int quantity = Common_util.getInt(records[0]);
				int quantityR = Common_util.getInt(records[1]);
				double netAmount = Common_util.getDouble(records[2]);
				double netAmountR = Common_util.getDouble(records[3]);
				ChainStoreSalesOrder salesOrder = new ChainStoreSalesOrder();
				salesOrder.setTotalQuantity(quantity);
				salesOrder.setTotalQuantityR(quantityR);
				salesOrder.setNetAmount(netAmount);
				salesOrder.setNetAmountR(netAmountR);
				orders.add(salesOrder);
			}
		}		
		return orders.get(0);
		
	}
	
	
	public List<EchartsInfoVO> getEchartsInfoDayVOs(ChainReportActionFormBean formBean,Boolean isHidden) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		List<EchartsInfoVO> list = new ArrayList<EchartsInfoVO>();
		List<Date> dates = DateUtils.findEveryDay(formBean.getStartDate(), formBean.getEndDate());
		
		// 获取当前年份时间段集合
		Map<String, ChainStoreSalesOrder> map = new HashMap<String, ChainStoreSalesOrder>();

			List<ChainStoreSalesOrder> orders = getChainStoreSalesOrders(formBean.getStartDate(),formBean.getEndDate(),formBean.getChainStore().getChain_id(),formBean.getSaler().getUser_id(),isHidden);
			if (orders.size() != 0) {
				for (ChainStoreSalesOrder chainStoreSalesOrder : orders) {
					map.put(format.format(chainStoreSalesOrder.getOrderDate()), chainStoreSalesOrder);
				}
			}
		
						
		// 获取当前年份上一年的时间段集合
		Map<String, ChainStoreSalesOrder> bMap = new HashMap<String, ChainStoreSalesOrder>();

		List<ChainStoreSalesOrder> beforeOrders = getChainStoreSalesOrders(new java.sql.Date(DateUtils.getBeforeYearDate(formBean.getStartDate()).getTime()),new java.sql.Date(DateUtils.getBeforeYearDate(formBean.getEndDate()).getTime()),formBean.getChainStore().getChain_id(),formBean.getSaler().getUser_id(),isHidden);
			if (beforeOrders.size() != 0) {
				for (ChainStoreSalesOrder chainStoreSalesOrder : beforeOrders) {
					bMap.put(format.format(chainStoreSalesOrder.getOrderDate()), chainStoreSalesOrder);
				}
			}
						
		if (dates.size() != 0) {
			for (Date date : dates) {
				EchartsInfoVO echartsInfoVO = new EchartsInfoVO();
				echartsInfoVO.setDateTime(format.format(date));
				
				ChainStoreSalesOrder beforeOrder = bMap.get(format.format(DateUtils.getBeforeYearDate(date)));
				ChainStoreSalesOrder order = map.get(format.format(date));
				if (beforeOrder != null) {
					echartsInfoVO.setBeforeQuantity(beforeOrder.getTotalQuantity() - beforeOrder.getTotalQuantityR());
					echartsInfoVO.setBeforeAmount((int) (beforeOrder.getNetAmount() - beforeOrder.getNetAmountR()));
				}else {
					echartsInfoVO.setBeforeQuantity(0);
					echartsInfoVO.setBeforeAmount(0);
				}
				if (order != null) {
					echartsInfoVO.setTodayQuantity(order.getTotalQuantity() - order.getTotalQuantityR());
					echartsInfoVO.setTodayAmount((int) (order.getNetAmount() - order.getNetAmountR()));
				}else {
					echartsInfoVO.setTodayQuantity(0);
					echartsInfoVO.setTodayAmount(0);
				}
				
				echartsInfoVO.setDifferQuantity(echartsInfoVO.getTodayQuantity() - echartsInfoVO.getBeforeQuantity());
				echartsInfoVO.setDifferAmount((int) (echartsInfoVO.getTodayAmount() - echartsInfoVO.getBeforeAmount()));
				list.add(echartsInfoVO);
			}
			
		}

				
		
		return list;
	}

	public List<EchartsInfoVO> getEchartsInfoWeekVOs(ChainReportActionFormBean formBean,Boolean isHidden) throws ParseException {
		List<EchartsInfoVO> list = new ArrayList<EchartsInfoVO>();
		//根据开始时间，获取开始时间所在周的周一时间
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = DateUtils.getWeekByDate(formBean.getStartDate());
		//根据结束时间，获取结束时间所在周的周日时间
		Date endDate = DateUtils.getLastDayOfWeek(formBean.getEndDate());
		//获取开始时间和结束时间直接的天数
		int diffDays = DateUtils.diffDays(format.format(startDate), format.format(endDate)) + 1;
		//周次数
		int weekCounts = diffDays/7;
		
		for (int i = 0; i < weekCounts; i++) {
			EchartsInfoVO echartsInfoVO = new EchartsInfoVO();
			if (i == 0) {
				Date beforeStartDate = DateUtils.getBeforeYearDate(startDate);//往年周一时间
				Date beforeEndDate = DateUtils.getDay(beforeStartDate, 6);//往年周天时间
				Date enDate = DateUtils.getDay(startDate, 6);				
				echartsInfoVO = getEchartsInfoVO(startDate, enDate, beforeStartDate, beforeEndDate,formBean.getChainStore().getChain_id(),formBean.getSaler().getUser_id(),isHidden);
				echartsInfoVO.setDateTime(format.format(startDate)+ "  至  " +format.format(enDate));
				list.add(echartsInfoVO);
			}else {				
				//周一
				Date monday = DateUtils.getDay(startDate, i*7);
				//周天 
				Date sunday = DateUtils.getDay(startDate, 6 + (i*7));
				Date beforeStartDate = DateUtils.getBeforeYearDate(monday);
				Date befordEndDate = DateUtils.getBeforeYearDate(sunday);
				echartsInfoVO = getEchartsInfoVO(monday, sunday, beforeStartDate, befordEndDate,formBean.getChainStore().getChain_id(),formBean.getSaler().getUser_id(),isHidden);
				echartsInfoVO.setDateTime(format.format(monday)+ "  至   " +format.format(sunday));
				list.add(echartsInfoVO);
			}
			
		}
				
		return  list;
		
	}
	
	

	public List<EchartsInfoVO> getEchartsInfoYearVOs(ChainReportActionFormBean formBean,Boolean isHidden) throws ParseException {
		List<EchartsInfoVO> list = new ArrayList<EchartsInfoVO>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		List<String> allMonth = DateUtils.getMonthBetweenDate(format.format(formBean.getStartDate()), format.format(formBean.getEndDate()));
		
		if (allMonth.size() != 0) {
			for (String monthDay : allMonth) {
				EchartsInfoVO echartsInfoVO = new EchartsInfoVO();
				//当月第一天
				Date monthFirstDay = format.parse(monthDay + "-01");
				int month = monthDay.indexOf(5);
				Date monthEndDay;
				if (month == 0) {
					 monthEndDay = DateUtils.getMonthEndDay(Integer.valueOf(monthDay.substring(0,4)),Integer.valueOf(monthDay.substring(6,monthDay.length())));
				}else {
					 monthEndDay = DateUtils.getMonthEndDay(Integer.valueOf(monthDay.substring(0,4)),Integer.valueOf(monthDay.substring(5,monthDay.length())));
				}
				
				Date beforeStartDate = DateUtils.getBeforeYearDate(monthFirstDay);
				Date befordEndDate = DateUtils.getBeforeYearDate(monthEndDay);
				echartsInfoVO = getEchartsInfoVO(monthFirstDay, monthEndDay, beforeStartDate, befordEndDate,formBean.getChainStore().getChain_id(),formBean.getSaler().getUser_id(),isHidden);
				echartsInfoVO.setDateTime(format.format(monthFirstDay)+ "  至   " +format.format(monthEndDay));
				list.add(echartsInfoVO);
			}
		}		
		return list;
	}
	
	
	private EchartsInfoVO getEchartsInfoVO(Date startDate,Date endDate, Date beforeDate,Date beforeEndDate,Integer chainId,Integer userId,Boolean isHidden) {
		EchartsInfoVO echartsInfoVO = new EchartsInfoVO();
		
		ChainStoreSalesOrder beforeOrder = getChainStoreSalesWeekOrders(beforeDate, beforeEndDate, chainId, userId,isHidden);
		ChainStoreSalesOrder order = getChainStoreSalesWeekOrders(startDate, endDate, chainId, userId,isHidden);
		if (beforeOrder != null) {
			echartsInfoVO.setBeforeQuantity(beforeOrder.getTotalQuantity() - beforeOrder.getTotalQuantityR());
			echartsInfoVO.setBeforeAmount((int) (beforeOrder.getNetAmount() - beforeOrder.getNetAmountR()));
		}else {
			echartsInfoVO.setBeforeQuantity(0);
			echartsInfoVO.setBeforeAmount(0);
		}
		
		
		if (order != null) {
			echartsInfoVO.setTodayQuantity(order.getTotalQuantity() - order.getTotalQuantityR());
			echartsInfoVO.setTodayAmount((int) (order.getNetAmount() - order.getNetAmountR()));
		}else {
			echartsInfoVO.setTodayQuantity(0);
			echartsInfoVO.setTodayAmount(0);
		}
		
		echartsInfoVO.setDifferQuantity(echartsInfoVO.getTodayQuantity() - echartsInfoVO.getBeforeQuantity());
		echartsInfoVO.setDifferAmount((int) (echartsInfoVO.getTodayAmount() - echartsInfoVO.getBeforeAmount()));
		return echartsInfoVO;
	}



	

}
